from flask import Blueprint, jsonify, request, redirect
from flask_restful import Api,reqparse,Resource
from models.user.user import *
from db import db


shopping_bp = Blueprint('shopping',__name__,url_prefix='/shop')
api = Api(shopping_bp)

# 展示数据购物车
class Getshopping(Resource):
    def get(self):
        req = reqparse.RequestParser()
        req.add_argument('userid')
        args = req.parse_args()
        list = []
        sql = "select * from cart where cart.userid=%d"%int(args['userid'])
        res = db.find_all(sql)
        print('1111',res)
        for i in res:
            sql1 = "select * from tcourse where tcourse.id=%d"%int(i['cid'])
            res1 = db.find_all(sql1)
            for j in res1:
                list.append({
                    'id':j['id'],
                    'title':j['title'],
                    'price':j['price'],
                    'count':i['count'],
                    'url':j['url'],
                    'amount':(j['price'] * i['count'])
                })
        return jsonify({'code':200,'msg':'ok','data':list})

api.add_resource(Getshopping,'/getshop')



# 购物车数量加
class Add_count(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('userid')
        req.add_argument('id')
        args = req.parse_args()
        print(args['id'],12222222222)

        if not all({args['id'],args['userid']}):
            return jsonify({'code':400,'msg':'数据不存在'})

        sql = "select * from cart where cart.userid = %d and cart.cid = %d"%(int(args['userid']),int(args['id']))
        res = db.find_all(sql)
        print(res,8888888)
        for i in res:
            sql1 = "update Cart set count=count+1 where cart.userid=%d and cart.cid=%d"%(int(i['userid']),int(args['id']))
            db.add(sql1)
            db.commit()
        return jsonify({'code':200,'msg':'加成功'})
api.add_resource(Add_count,'/addcount')


# 购物车数量减
class Min_count(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('userid')
        req.add_argument('id')
        args = req.parse_args()
        print(args['id'], 12222222222)

        if not all({args['id'], args['userid']}):
            return jsonify({'code': 400, 'msg': '数据不存在'})

        sql = "select * from cart where cart.userid = %d and cart.cid = %d" % (int(args['userid']), int(args['id']))
        res = db.find_all(sql)
        print(res, 8888888)
        for i in res:
            sql1 = "update Cart set count=count-1 where cart.userid=%d and cart.cid=%d" % (int(i['userid']), int(args['id']))
            db.add(sql1)
            db.commit()
        return jsonify({'code':200,'msg':'减成功'})
api.add_resource(Min_count,'/mincount')

# 删除购物车数据
class Del_count(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('userid')
        req.add_argument('id')
        args = req.parse_args()

        if not all({args['id'], args['userid']}):
            return jsonify({'code': 400, 'msg': '数据不存在'})

        sql = "select * from cart where cart.userid = %d and cart.cid = %d" % (int(args['userid']), int(args['id']))
        res = db.find_all(sql)
        for i in res:
            sql1 = "delete from Cart where cart.userid=%d and cart.cid=%d" % (int(i['userid']), int(args['id']))
            db.add(sql1)
            db.commit()
        return jsonify({'code':200,'msg':'ok'})
api.add_resource(Del_count,'/delcount')



# 合计
# class Getshopp(Resource):
#     def get(self):
#         req = reqparse.RequestParser()
#         req.add_argument('userid')
#         args = req.parse_args()
#         list = []
#         sql = "select * from cart where cart.userid=%d"%int(args['userid'])
#         res = db.find_all(sql)
#         for i in res:
#             sql1 = "select * from tcourse where tcourse.id=%d"%int(i['cid'])
#             res1 = db.find_all(sql1)
#             for j in res1:
#                 list.append({
#                     'id':j['id'],
#                     'title':j['title'],
#                     'price':j['price'],
#                     'count':i['count'],
#                     'url':j['url'],
#                     'amount':(j['price'] * i['count'])
#                 })
#         return jsonify({'code':200,'msg':'ok','data':list})
#
# api.add_resource(Getshopp,'/getshopp')



import random
import time
from utils.comm import get_ali_object
# 调用支付宝  进行购买
class Zf_shop(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('userid')
        args = req.parse_args()
        money = 200
        tmoney = money * int(10)
        order_no = str(int(time.time())) + str(args['userid']) + str(random.randint(100,999))
        vip = VipRecord(order_no=order_no, userid=args['userid'],  money=tmoney, active_money=tmoney,status=2)
        # 支付页面 支付
        pay = get_ali_object()
        query_params = pay.direct_pay(
            subject='购物车订单',  # 商品简单描述
            out_trade_no=str(order_no),  # 用户购买的商品订单号（每次不一样） 20180301073422891
            total_amount=tmoney,  # 交易金额(单位: 元 保留俩位小数)
        )
        pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
        return jsonify({
            'code': 200,
            'url': pay_url
        })

api.add_resource(Zf_shop,'/zfshop')

#  支付宝回调接口
class Callback(Resource):
    def get(self):
        #     try:
        #         sql = "update orders set status=3"
        #         db.session.add(sql)
        #         db.session.commit()
        #     except:
        #         db.session.rollback()
        #     # 跳转到个人中心
        #     return redirect('http://localhost:8080/#/')
        data = request.args
        datames = {k: v for k, v in data.items()}
        # 删除字典中key为sign的记录
        sign = datames.pop('sign')
        # 鉴权
        pay = get_ali_object()
        flag = pay.verify(datames, sign)
        print(flag)
        if flag == True:
            # 订单号
            order_no = datames["out_trade_no"]
            # 事务处理
            try:
                # 订单号更新订单表
                print(order_no)
                record = Orders.query.filter(Orders.number == order_no).first()
                record.status = 3
                db.session.add(record)
                db.session.commit()
            except:
                db.session.rollback()
        else:
            print("鉴权失败")
        # 跳转到个人中心
            return redirect('http://localhost:8080/#/')
        return redirect('http://localhost:8080/#/cart')

api.add_resource(Callback,'/callback')


